/**
 * 活动抽奖页面
 */

import {
  getTimeList,
  saveUserInfo,
  timeListener,
} from '/utils';
import * as api from '/common/api';

Page({
  data: {
    activityTimeList: {}, // 活动时间列表
    activityTimeListKeys: [],
    hasAuth: false,
    hide: true,
  },

  onShow() {
    this.setData({ hide: false });
    this.handleGetUserAuth();
  },

  onHide() {
    // 停止倒计时
    timeListener(null, null, null, true);
    this.setData({ hide: true });
  },

  // 请求用户授权
  handleGetUserAuth() {
    my.getAuthCode({
      scopes: 'auth_user',
      success: (res) => {
        my.showLoading();
        const { authCode } = res;
        api.userAuth(authCode).then((res) => {
          // 保存信息到sessionStorage中
          saveUserInfo(res);
          this.setData({
            hasAuth: true,
          });
          my.hideLoading();
          this.handleGetTimeList();
        }).catch((err) => {
          console.log(err);
        });
      },
      fail: () => {
        my.navigateBack();
      }
    });
  },

  // 设置活动时间
  handleGetTimeList() {
    getTimeList()
      .then((res) => {
        if (res) {
          this.setData({ 
            activityTimeList: res,
            activityTimeListKeys: Object.keys(res),
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
});
